package com.example.demo.util;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class RESTUtil {
    private String user;
    private String password;
    private String url;
    private String requestBody;
    private Cookie[] cookies;
    private Map<String, String> requestPropertyMap;
    private String contentType = "application/json;charset=UTF-8";
    HttpClient httpClient;

    public RESTUtil(String url, String requestBody, Cookie[] cookies, String user, String password) throws Exception {
        this.url = url;
        this.requestBody = requestBody;
        this.cookies = cookies;
        this.user=user;
        this.password=password;
    }

    public Cookie[] getCookies() {
        if (this.httpClient != null) {
            return httpClient.getState().getCookies();
        } else {
            return null;
        }
    }

    public void setRequestProperty(Map<String, String> requestPropertyMap) {
        this.requestPropertyMap = requestPropertyMap;
    }

    public String loadPost() throws Exception {
        return postMethod();
    }
    public String loadGet() throws Exception {
        return getMethod();
    }
    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    private String getMethod() throws IOException {
        GetMethod getMethod = new GetMethod(this.url);
        // 执行postMethod
        if (httpClient == null) {
            httpClient = new HttpClient();
            if(StringUtils.isNotBlank(this.user)&&StringUtils.isNotBlank(this.password)){
                httpClient.getState().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(this.user, this.password));
            }
        }
        getMethod.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        String charSet=getMethod.getResponseCharSet();
        int statusCode = httpClient.executeMethod(getMethod);
        // HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
        StringBuffer contentBuffer = new StringBuffer();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream in = getMethod.getResponseBodyAsStream();
            if(StringUtils.isNotBlank(getMethod.getRequestCharSet())){
                charSet=getMethod.getRequestCharSet();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(in,charSet));
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                contentBuffer.append(inputLine);
            }
            in.close();

        }
        System.out.println(contentBuffer.toString());
        return contentBuffer.toString();
    }

    private String postMethod() throws IOException {
        PostMethod postMethod = new PostMethod(this.url);
        postMethod.setRequestBody(this.requestBody);
        postMethod.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        postMethod.setRequestHeader("Content-Type", this.contentType);

        if (requestPropertyMap != null && requestPropertyMap.size() > 0) {
            Set<String> keys = requestPropertyMap.keySet();
            for (Iterator<String> iterator = keys.iterator(); iterator.hasNext(); ) {
                String key = iterator.next();
                postMethod.setRequestHeader(key, requestPropertyMap.get(key));
            }
        }
        if (httpClient == null) {
            httpClient = new HttpClient();
            if(StringUtils.isNotBlank(this.user)&&StringUtils.isNotBlank(this.password)){
                httpClient.getState().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(this.user, this.password));
            }
        }
        //Cookie[] cookies = httpClient.getState().getCookies();
        if (this.cookies != null) {
            HttpState state = new HttpState();
            state.addCookies(this.cookies);
            httpClient.setState(state);
        }

        // 执行postMethod
        int statusCode = httpClient.executeMethod(postMethod);
        // HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发

        StringBuffer contentBuffer = new StringBuffer();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream in = postMethod.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, postMethod.getResponseCharSet()));
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                contentBuffer.append(inputLine);
            }
            in.close();

        }
        return contentBuffer.toString();
    }

    public String getRequestBody() {
        return requestBody;
    }

    public void setRequestBody(String requestBody) {
        this.requestBody = requestBody;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
